Angular 폼을 만들기 위해서는 다음과 같은 스텝이 필요하다.

  1. 모델 생성

  2. 폼 컨트롤러 컴포넌트를 생성

  3. 앱 모듈에 작성한 폼컴포넌트추가.

  4. 템플릿 생성, ngModel로 양방향 데이터 바인딩을 함

  5. 폼 검증을 수행

  6. ngSubmit을 통해 submit을 컨트롤

Step 1. 모델 생성

생성자의 인자로 public 을 사용하면, 자동으로 해당 모델에 변수 값을 선언함.

1
2
3
4
5
6
7
8
9
10
export class Prescription {
constructor(
public psNo: number,
public userNo: number,
public mainDiseaseCd: string,
public subDiseaseCd: string,
public drugCd: string,
public timeDivision: string
) { }
}

Step2. 폼 컨트롤러

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Component } from '@angular/core';
import { Prescription } from './prescription.model';

@Component({
selector: 'page-prescription',
templateUrl: 'prescription.html'
})
export class PrescriptionComponent {
// user = { userId: '', userName: '' };
timeDivison = ['MOR', 'EVE', 'NOON', 'NIGHT'];
model = new Prescription(1, 1, "abc", "def", "aa", this.timeDivison[0]);
submitted = false;

onSubmit() {
}
// 테스트를 위함
get diagnostic() { return JSON.stringify(this.model) }
}

Step3. 앱 모듈

작성한 폼 컴포넌트를 추가한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { PrescriptionComponent } from './prescription.component';

@NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [
AppComponent,
PrescriptionComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
  • BrowserModule : 브라우저에서 실행하기 위한 모듈, 컴포넌트나 지시자, 파이프 같은 구성요소를 템플릿에 나타나게 하는 역할.
  • FormsModule : NgModel 지시자나 내장 검증기 지시자 등을 포함.
  • delarations : imports에 입력한 모듈 내에서 선언된 내용들을 재선언 해서는 안된다.

Step 4. 템플릿 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{{diagnostic}}
<form #prescriptionForm="ngForm">
<div>
<label for="mainDiseaseCd">Main Disease CD</label>
<input type="text" id="mainDiseaseCd" required [(ngModel)]="model.mainDiseaseCd" name="mainDiseaseCd">
</div>

<div>
<label for="subDiseaseCd">Sub Disease Cd</label>
<input type="text" id="subDiseaseCd" required [(ngModel)]="model.subDiseaseCd" name="subDiseaseCd">
</div>

<div>
<label for="timeDivision">Time Division</label>
<select id="timeDivision" required [(ngModel)]="model.timeDivision" name="timeDivision" #timeDivision="ngModel">
<option *ngFor="let timeDivision of timeDivisions" [value]="timeDivision">{{timeDivision}}</option>
</select>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
  • #prescriptionForm="ngForm" : 해당 폼을 ngForm이 관리하도록 함. ngModel과 name 속성을 사용하여, 속성을 모니터링 함.
  • required: 내장 검증기로, 필수값을 의미. 그외에도 minlength, maxlength, pattern 가 있다.
  • [(ngModel)]="model.mainDiseaseCd" name="mainDiseaseCd" : ngModel과 name은 함께 선언해 주어야함. name 프로퍼티는 폼과 함께 컨트롤러에 등록되기 위해 필요하다.
  • <label for="timeDivision"> : input id태그와 label for 속성이 연결된다.
  • #timeDivision="ngModel": 검증 결과를 확인하기 위해 timeDivision 참조변수에 ngModel을 할당한다. timeDivision.valid로 검증 결과를 확인할 수 있다.

Step 5. 폼 검증 수행

  • 템플릿 파일 폼 검증 결과 문구 추가
1
2
3
4
5
6
7
8
9
...
<div>
<label for="mainDiseaseCd">Main Disease CD</label>
<input type="text" id="mainDiseaseCd" required [(ngModel)]="model.mainDiseaseCd" name="mainDiseaseCd" #mainDiseaseCd="ngModel">
</div>
<div [hidden]="mainDiseaseCd.valid || mainDiseaseCd.pristine">
mainDiseaseCd is required
</div>
...

#mainDiseaseCd="ngModel": 검증 결과를 확인하기 위해 mainDiseaseCd참조변수에 ngModel을 할당한다. mainDiseaseCd.valid로 검증 결과를 확인할 수 있다.

  • css
1
2
3
4
5
6
7
.ng-valid[required], .ng-valid.required  {
border-left: 5px solid #42A948; /* green */
}

.ng-invalid:not(form) {
border-left: 5px solid #a94442; /* red */
}

Step 6. submit 컨트롤

다음과 같이 수정한다.

1
<form (ngSubmit)="onSubmit()" #prescriptionForm="ngForm">

Reference

https://angular.io/guide/forms#create-an-initial-html-form-template